import axios, { AxiosError, AxiosResponse } from 'axios';
import { ApiError, ApiResponse, Commit, Repository, RepositoryFile, User } from '@/types';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080/api';

// 创建axios实例
const api = axios.create({
  baseURL: API_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 从localStorage获取token
    const token = typeof window !== 'undefined' ? localStorage.getItem('accessToken') : null;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
api.interceptors.response.use(
  (response) => response,
  async (error: AxiosError) => {
    const originalRequest: any = error.config;
    // 如果是401错误且没有重试过，尝试刷新token
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      try {
        const refreshToken = localStorage.getItem('refreshToken');
        if (refreshToken) {
          const response = await axios.post(`${API_URL}/auth/refresh`, { refresh_token: refreshToken });
          const { accessToken } = response.data;
          localStorage.setItem('accessToken', accessToken);
          originalRequest.headers.Authorization = `Bearer ${accessToken}`;
          return api(originalRequest);
        }
      } catch (refreshError) {
        // 刷新token失败，清除登录信息并跳转到登录页
        localStorage.removeItem('accessToken');
        localStorage.removeItem('refreshToken');
        if (typeof window !== 'undefined') {
          window.location.href = '/login';
        }
      }
    }
    return Promise.reject(error);
  }
);

// 用户相关API
export const userApi = {
  // 获取登录URL
  getLoginUrl: async (): Promise<string> => {
    const response = await api.get<{ loginUrl: string }>('/auth/login');
    return response.data.loginUrl;
  },

  // 处理OAuth回调
  handleCallback: async (code: string): Promise<User> => {
    const response = await api.post<User>('/auth/callback', { code });
    return response.data;
  },

  // 获取当前用户信息
  getCurrentUser: async (): Promise<User> => {
    const response = await api.get<User>('/auth/user');
    return response.data;
  },

  // 刷新token
  refreshToken: async (refreshToken: string): Promise<{ accessToken: string }> => {
    const response = await api.post<{ accessToken: string }>('/auth/refresh', { refresh_token: refreshToken });
    return response.data;
  },
};

// 仓库相关API
export const repoApi = {
  // 获取用户仓库列表
  getUserRepositories: async (): Promise<Repository[]> => {
    const response = await api.get<Repository[]>('/repos');
    return response.data;
  },

  // 获取仓库详情
  getRepository: async (owner: string, repo: string): Promise<Repository> => {
    const response = await api.get<Repository>(`/repos/${owner}/${repo}`);
    return response.data;
  },

  // 获取仓库内容
  getRepositoryContents: async (owner: string, repo: string, path: string = '', ref?: string): Promise<RepositoryFile[]> => {
    const params = ref ? { ref } : {};
    const response = await api.get<RepositoryFile[]>(`/repos/${owner}/${repo}/contents${path ? `/${path}` : ''}`, { params });
    return response.data;
  },

  // 获取文件内容
  getRepositoryFile: async (owner: string, repo: string, path: string, ref?: string): Promise<RepositoryFile> => {
    const params = ref ? { ref } : {};
    const response = await api.get<RepositoryFile>(`/repos/${owner}/${repo}/contents/${path}`, { params });
    return response.data;
  },

  // 获取提交历史
  getRepositoryCommits: async (owner: string, repo: string, branch?: string): Promise<Commit[]> => {
    const params = branch ? { branch } : {};
    const response = await api.get<Commit[]>(`/repos/${owner}/${repo}/commits`, { params });
    return response.data;
  },

  // 创建提交
  createCommit: async (owner: string, repo: string, path: string, content: string, message: string, branch?: string): Promise<Commit> => {
    const params = branch ? { message, branch } : { message };
    const response = await api.post<Commit>(`/repos/${owner}/${repo}/contents/${path}`, content, { params });
    return response.data;
  },

  // 获取分支列表
  getRepositoryBranches: async (owner: string, repo: string): Promise<string[]> => {
    const response = await api.get<string[]>(`/repos/${owner}/${repo}/branches`);
    return response.data;
  },
};

export default api;